package com.cssp.dao.hibernate;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.cssp.dao.ITaskDao;
import com.cssp.dao.hibernate.base.HibernateBaseDao;
import com.cssp.model.auth.Company;
import com.cssp.model.witkey.Task;
import com.cssp.model.witkey.TaskClassify;
import com.cssp.model.witkey.TaskState;

public class TaskDao extends HibernateBaseDao<Task> implements ITaskDao {

	@SuppressWarnings("unchecked")
	public List<Task> find(TaskClassify classify, TaskState state,
			String order, int firstResult, int maxResult) {

		String hql = 
				"FROM Task t WHERE t.classify=:classify and t.state=:state ORDER BY t." + order;
		Map values = new HashMap();
		values.put("classify", classify);
		values.put("state", state);
		return findByHql(hql, values, firstResult, maxResult);
	}

	@SuppressWarnings("unchecked")
	public List<Task> find(TaskState state, String order, int firstResult,
			int maxResult) {
		
		String hql = 
			"FROM Task t WHERE t.state=:state ORDER BY t." + order;
		Map values = new HashMap();
		values.put("state", state);
		return findByHql(hql, values, firstResult, maxResult);
	}
	
	@SuppressWarnings("unchecked")
	public List<Task> find(Company owner,TaskState state ,String order,int firstResult,int maxResult){
		String hql="FROM Task t WHERE t.owner=:owner AND t.state=:state ORDER BY t."+order;
		Map values=new HashMap();
		values.put("owner", owner);
		values.put("state", state);
		return findByHql(hql, values, firstResult, maxResult);
	}
	@SuppressWarnings("unchecked")
	public List<Task> find(Company owner,String order,int firstResult,int maxResult){
		String hql="FROM Task t WHERE t.owner=:owner  ORDER BY t."+order;
		Map values=new HashMap();
		values.put("owner", owner);
		return findByHql(hql, values, firstResult, maxResult);
	
		
	}
	
	public Long count(final Company owner) {
		Long countRow=(Long)getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Long countRow =(Long)session.createQuery("select count(*) from Task t where t.owner=:owner")
				.setEntity("owner", owner)
				.uniqueResult();
			

				return countRow;
			} 
		});
		return countRow;
	}
	public Long count(final Company owner,final TaskState state) {
		Long countRow=(Long)getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Long countRow =(Long)session.createQuery("select count(*) from Task t where t.owner=:owner and t.state=:state")
				.setEntity("owner", owner)
				.setParameter("state",state)
				.uniqueResult();
			

				return countRow;
			} 
		});
		return countRow;
	}
}
